<template>
  <div class="plan-management">
    <!-- 统计概览 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ totalPlans }}</div>
                <div class="stats-label">预案总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon active">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ activePlans }}</div>
                <div class="stats-label">生效预案</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon draft">
                <el-icon><Edit /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ draftPlans }}</div>
                <div class="stats-label">草稿预案</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon executed">
                <el-icon><VideoPlay /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ executedPlans }}</div>
                <div class="stats-label">已执行</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" :inline="true" label-width="80px">
        <el-form-item label="预案名称">
          <el-input
            v-model="queryForm.planName"
            placeholder="请输入预案名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="预案类型">
          <el-select v-model="queryForm.planType" placeholder="请选择预案类型" clearable style="width: 150px">
            <el-option label="防洪预案" value="flood_control" />
            <el-option label="抗旱预案" value="drought_control" />
            <el-option label="应急预案" value="emergency" />
            <el-option label="维护预案" value="maintenance" />
            <el-option label="安全预案" value="safety" />
          </el-select>
        </el-form-item>
        <el-form-item label="预案状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="草稿" value="draft" />
            <el-option label="审核中" value="reviewing" />
            <el-option label="生效" value="active" />
            <el-option label="已废止" value="obsolete" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryForm.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增预案</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Download" @click="handleExport">导出数据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Upload" @click="handleImport">导入预案</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Clock" @click="showVersionDialog = true">版本管理</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button plain icon="DocumentCopy" @click="showTemplateDialog = true">预案模板</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="planName" label="预案名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="planType" label="预案类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getPlanTypeTagType(row.planType)">
              {{ getPlanTypeText(row.planType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本号" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTagType(row.priority)">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="lastExecuteTime" label="最后执行" width="160" />
        <el-table-column prop="executeCount" label="执行次数" width="100" />
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="warning" icon="VideoPlay" @click="handleExecute(scope.row)">执行</el-button>
            <el-button link type="info" icon="DocumentCopy" @click="handleCopy(scope.row)">复制</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <Pagination
          :total="pagination.total"
          v-model:page="pagination.currentPage"
          v-model:limit="pagination.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <!-- 预案表单对话框 -->
    <PlanFormDialog
      v-model:visible="showFormDialog"
      :form-data="currentRow"
      :is-edit="isEdit"
      @success="handleFormSuccess"
    />

    <!-- 预案详情对话框 -->
    <PlanDetailDialog
      v-model:visible="showDetailDialog"
      :plan-data="currentRow"
    />

    <!-- 预案执行对话框 -->
    <PlanExecuteDialog
      v-model:visible="showExecuteDialog"
      :plan-data="currentRow"
      @success="handleExecuteSuccess"
    />

    <!-- 版本管理对话框 -->
    <VersionManageDialog
      v-model:visible="showVersionDialog"
      :plan-data="currentRow"
    />

    <!-- 预案模板对话框 -->
    <PlanTemplateDialog
      v-model:visible="showTemplateDialog"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Download,
  Upload,
  Clock,
  DocumentCopy,
  Document,
  CircleCheck,
  Edit,
  VideoPlay
} from '@element-plus/icons-vue'
import PlanFormDialog from './components/PlanFormDialog.vue'
import PlanDetailDialog from './components/PlanDetailDialog.vue'
import PlanExecuteDialog from './components/PlanExecuteDialog.vue'
import VersionManageDialog from './components/VersionManageDialog.vue'
import PlanTemplateDialog from './components/PlanTemplateDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const tableLoading = ref(false)
const showFormDialog = ref(false)
const showDetailDialog = ref(false)
const showExecuteDialog = ref(false)
const showVersionDialog = ref(false)
const showTemplateDialog = ref(false)
const isEdit = ref(false)
const currentRow = ref({})
const selectedRows = ref([])

// 查询表单
const queryForm = reactive({
  planName: '',
  planType: '',
  status: '',
  createTimeRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    planName: '汛期防洪应急预案',
    planType: 'flood_control',
    version: 'v2.1',
    status: 'active',
    priority: 'high',
    creator: '张三',
    createTime: '2024-01-15 10:30:00',
    lastExecuteTime: '2024-06-20 14:20:00',
    executeCount: 3,
    description: '针对汛期可能发生的洪水灾害制定的应急预案'
  },
  {
    id: 2,
    planName: '干旱期供水保障预案',
    planType: 'drought_control',
    version: 'v1.5',
    status: 'active',
    priority: 'medium',
    creator: '李四',
    createTime: '2024-02-10 09:15:00',
    lastExecuteTime: '2024-08-15 11:30:00',
    executeCount: 2,
    description: '干旱期间确保供水安全的应急预案'
  },
  {
    id: 3,
    planName: '设备故障应急预案',
    planType: 'emergency',
    version: 'v1.0',
    status: 'reviewing',
    priority: 'high',
    creator: '王五',
    createTime: '2024-03-05 16:45:00',
    lastExecuteTime: '-',
    executeCount: 0,
    description: '主要设备发生故障时的应急处理预案'
  },
  {
    id: 4,
    planName: '年度维护保养预案',
    planType: 'maintenance',
    version: 'v3.0',
    status: 'draft',
    priority: 'low',
    creator: '赵六',
    createTime: '2024-04-12 14:20:00',
    lastExecuteTime: '2024-05-10 08:00:00',
    executeCount: 1,
    description: '年度设备维护保养计划预案'
  },
  {
    id: 5,
    planName: '安全生产应急预案',
    planType: 'safety',
    version: 'v2.0',
    status: 'active',
    priority: 'high',
    creator: '孙七',
    createTime: '2024-05-08 11:10:00',
    lastExecuteTime: '-',
    executeCount: 0,
    description: '安全生产事故应急处理预案'
  }
])

// 统一模拟数据与筛选分页
const allData = ref<any[]>([])
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]) => arr[randInt(0, arr.length - 1)]
const pad2 = (n: number) => (n < 10 ? `0${n}` : `${n}`)
const formatISODateTime = (date: Date) => `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`

const generateMockData = () => {
  const types = ['flood_control', 'drought_control', 'emergency', 'maintenance', 'safety']
  const statuses = ['draft', 'reviewing', 'active', 'obsolete']
  const priorities = ['low', 'medium', 'high']
  const creators = ['张三', '李四', '王五', '赵六', '孙七']
  const names = ['防洪应急', '供水保障', '设备故障', '维护保养', '安全生产']
  const cnt = randInt(30, 80)
  const data = Array.from({ length: cnt }, (_, i) => {
    const planType = randomChoice(types)
    const status = randomChoice(statuses)
    const priority = randomChoice(priorities)
    const name = `${randomChoice(names)}预案_${i + 1}`
    const create = new Date(Date.now() - randInt(0, 90) * 24 * 3600 * 1000)
    const lastExec = randInt(0, 1) === 1 ? new Date(Date.now() - randInt(0, 30) * 24 * 3600 * 1000) : null
    return {
      id: Date.now() + i,
      planName: name,
      planType,
      version: `v${randInt(1, 3)}.${randInt(0, 9)}`,
      status,
      priority,
      creator: randomChoice(creators),
      createTime: formatISODateTime(create),
      lastExecuteTime: lastExec ? formatISODateTime(lastExec) : '-',
      executeCount: lastExec ? randInt(1, 5) : 0,
      description: `关于${name}的说明`
    }
  })
  allData.value = data
}

const applyFiltersAndPaginate = () => {
  const { planName, planType, status, createTimeRange } = queryForm
  let filtered = allData.value.slice()
  if (planName) {
    filtered = filtered.filter(d => d.planName?.includes(planName))
  }
  if (planType) {
    filtered = filtered.filter(d => d.planType === planType)
  }
  if (status) {
    filtered = filtered.filter(d => d.status === status)
  }
  if (createTimeRange && createTimeRange.length === 2) {
    const [start, end] = createTimeRange
    const s = new Date(start).getTime()
    const e = new Date(end).getTime() + 24 * 3600 * 1000 - 1
    filtered = filtered.filter(d => {
      const t = new Date(d.createTime).getTime()
      return t >= s && t <= e
    })
  }
  pagination.total = filtered.length
  const startIdx = (pagination.currentPage - 1) * pagination.pageSize
  const endIdx = startIdx + pagination.pageSize
  tableData.value = filtered.slice(startIdx, endIdx)
}

// 统计数据
const totalPlans = computed(() => tableData.value.length)
const activePlans = computed(() => tableData.value.filter(item => item.status === 'active').length)
const draftPlans = computed(() => tableData.value.filter(item => item.status === 'draft').length)
const executedPlans = computed(() => tableData.value.filter(item => item.executeCount > 0).length)

// 获取预案类型标签类型
const getPlanTypeTagType = (type: string) => {
  const typeMap = {
    flood_control: 'primary',
    drought_control: 'success',
    emergency: 'danger',
    maintenance: 'warning',
    safety: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取预案类型文本
const getPlanTypeText = (type: string) => {
  const typeMap = {
    flood_control: '防洪预案',
    drought_control: '抗旱预案',
    emergency: '应急预案',
    maintenance: '维护预案',
    safety: '安全预案'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap = {
    draft: 'info',
    reviewing: 'warning',
    active: 'success',
    obsolete: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    draft: '草稿',
    reviewing: '审核中',
    active: '生效',
    obsolete: '已废止'
  }
  return statusMap[status] || status
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const priorityMap = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return priorityMap[priority] || priority
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 重置
const handleReset = () => {
  Object.keys(queryForm).forEach(key => {
    // @ts-ignore
    queryForm[key] = ''
  })
  queryForm.createTimeRange = []
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 新增
const handleAdd = () => {
  currentRow.value = {}
  isEdit.value = false
  showFormDialog.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentRow.value = { ...row }
  isEdit.value = true
  showFormDialog.value = true
}

// 查看
const handleView = (row: any) => {
  currentRow.value = { ...row }
  showDetailDialog.value = true
}

// 执行
const handleExecute = (row: any) => {
  currentRow.value = { ...row }
  showExecuteDialog.value = true
}

// 复制
const handleCopy = (row: any) => {
  const newPlan = {
    ...row,
    id: Date.now(),
    planName: `${row.planName}_副本`,
    version: 'v1.0',
    status: 'draft',
    createTime: new Date().toLocaleString(),
    lastExecuteTime: '-',
    executeCount: 0
  }
  allData.value.unshift(newPlan)
  applyFiltersAndPaginate()
  ElMessage.success('预案复制成功')
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除预案 "${row.planName}" 吗？`, '确认删除', {
    type: 'warning'
  }).then(() => {
    const index = allData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      allData.value.splice(index, 1)
      applyFiltersAndPaginate()
      ElMessage.success('删除成功')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个预案吗？`, '确认删除', {
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(row => row.id)
    allData.value = allData.value.filter(item => !ids.includes(item.id))
    selectedRows.value = []
    applyFiltersAndPaginate()
    ElMessage.success('批量删除成功')
  })
}

// 导出
const handleExport = () => {
  ElMessage.success('正在导出数据...')
}

// 导入
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页处理
const handlePagination = (page: any) => {
  pagination.currentPage = page.page
  pagination.pageSize = page.limit
  applyFiltersAndPaginate()
}

// 表单成功回调
const handleFormSuccess = () => {
  showFormDialog.value = false
  applyFiltersAndPaginate()
}

// 执行成功回调
const handleExecuteSuccess = () => {
  showExecuteDialog.value = false
  applyFiltersAndPaginate()
}

// 获取表格数据
const fetchTableData = async () => {
  tableLoading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 200))
    if (allData.value.length === 0) {
      generateMockData()
    }
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchTableData()
})

</script>

<style scoped>
.plan-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.stats-overview {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  overflow: hidden;
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stats-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.active {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.draft {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.executed {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-value {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-button + .el-button) {
  margin-left: 0;
}
</style>